import React, { useState, useEffect } from 'react';
import { Table, Button, Tag, message, Space, Tooltip, Modal } from 'antd';
import { ExclamationCircleOutlined, StopOutlined, PieChartOutlined, TeamOutlined } from '@ant-design/icons';
import axios from 'axios';
import moment from 'moment';

const { confirm } = Modal;

const SignInTaskList = ({ courseId, refreshTrigger, onViewStudents, onViewStats }) => {
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(false);
  
  // 获取签到任务列表
  const fetchSignInTasks = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`/teacher/sign_in/tasks?course_id=${courseId}`);
      if (response.data && (response.data.code === 2000 || response.data.code === 0)) {
        const taskData = response.data.data || [];
        setTasks(taskData);
      } else {
        message.error('获取签到任务失败');
      }
    } catch (error) {
      console.error('获取签到任务出错:', error);
      message.error('获取签到任务出错，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 结束签到任务
  const endSignInTask = async (taskId) => {
    try {
      const response = await axios.post('/teacher/sign_in/end', { task_id: taskId });
      if (response.data && (response.data.code === 2000 || response.data.code === 0)) {
        message.success('签到任务已结束');
        fetchSignInTasks(); // 刷新列表
      } else {
        message.error(`操作失败: ${response.data?.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('结束签到任务出错:', error);
      message.error(error.response?.data?.message || '操作失败，请重试');
    }
  };

  // 确认结束签到任务
  const showEndConfirm = (taskId, taskDescription) => {
    confirm({
      title: '结束签到任务',
      icon: <ExclamationCircleOutlined />,
      content: `确定要结束"${taskDescription}"签到任务吗？结束后学生将无法继续签到。`,
      onOk() {
        return endSignInTask(taskId);
      },
    });
  };

  // 处理查看签到统计
  const handleViewStats = (taskId) => {
    if (onViewStats) {
      onViewStats(taskId);
    } else {
      message.info(`查看签到统计 ID: ${taskId}`);
    }
  };

  // 处理查看学生签到列表
  const handleViewStudents = (taskId) => {
    if (onViewStudents) {
      onViewStudents(taskId);
    } else {
      message.info(`查看签到学生 ID: ${taskId}`);
    }
  };

  // 格式化时间戳为日期时间
  const formatTime = (timestamp) => {
    if (!timestamp) return '-';
    
    try {
      // 确保时间戳是毫秒级的
      const milliseconds = timestamp > 10000000000 ? timestamp : timestamp * 1000;
      
      // 创建日期对象
      const date = new Date(milliseconds);
      
      // 使用本地时区格式化时间
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return String(timestamp);
    }
  };

  // 获取任务状态标签
  const getStatusTag = (status, startTime, endTime) => {
    const now = Math.floor(Date.now() / 1000);
    
    if (status === 2) {
      return <Tag color="default">已结束</Tag>;
    }
    
    if (now < startTime) {
      return <Tag color="blue">未开始</Tag>;
    }
    
    if (now > endTime) {
      return <Tag color="red">已过期</Tag>;
    }
    
    return <Tag color="green">进行中</Tag>;
  };

  // 初次加载和courseId变化时获取数据
  useEffect(() => {
    if (courseId) {
      fetchSignInTasks();
    }
  }, [courseId, refreshTrigger]);

  // 表格列定义
  const columns = [
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      render: (text) => formatTime(text),
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      key: 'end_time',
      render: (text) => formatTime(text),
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => getStatusTag(record.status, record.start_time, record.end_time),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        const now = Math.floor(Date.now() / 1000);
        const isActive = record.status === 1 && now >= record.start_time && now <= record.end_time;
        
        return (
          <Space size="small">
            {isActive && (
              <Tooltip title="结束签到">
                <Button 
                  type="primary" 
                  danger 
                  icon={<StopOutlined />} 
                  size="small"
                  onClick={() => showEndConfirm(record.id, record.description)}
                />
              </Tooltip>
            )}
            <Tooltip title="查看统计">
              <Button 
                type="primary" 
                icon={<PieChartOutlined />} 
                size="small"
                onClick={() => handleViewStats(record.id)}
              />
            </Tooltip>
            <Tooltip title="查看学生">
              <Button 
                type="default" 
                icon={<TeamOutlined />} 
                size="small"
                onClick={() => handleViewStudents(record.id)}
              />
            </Tooltip>
          </Space>
        );
      },
    },
  ];

  return (
    <div className="sign-in-task-list">
      <Table 
        columns={columns} 
        dataSource={tasks} 
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 5 }}
        locale={{ emptyText: '暂无签到任务' }}
      />
    </div>
  );
};

export default SignInTaskList; 